package asyncTasks;

import java.io.IOException;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpParser;
import com.google.api.client.json.jackson.JacksonFactory;

import basicClasses.PlaceList;

import android.os.AsyncTask;
import android.util.Log;

public class GetNearbyPlaces extends AsyncTask<String, Void, PlaceList> {

	private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

	@Override
	protected PlaceList doInBackground(String... location) {
			try {
				HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
	            HttpRequest request;
					request = httpRequestFactory
					        .buildGetRequest(new GenericUrl("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"));
		            request.getUrl().put("key", "AIzaSyDspt3tRVqb0O0QhXhyn07AiVFWiB0mF40");
		            request.getUrl().put("location", location[0]);
		            request.getUrl().put("radius", "1500"); // in meters
		            request.getUrl().put("sensor", "false");
		            
		            PlaceList list = request.execute().parseAs(PlaceList.class);
		            // Check log cat for places response status
		            Log.d("Places Status", "" + list.status);
		            return list;
	 
	        } catch (HttpResponseException e) {
	            Log.e("Error:", e.getMessage());
	            return null;
	        } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;

	}
	
	public static HttpRequestFactory createRequestFactory(
            final HttpTransport transport) {
        return transport.createRequestFactory(new HttpRequestInitializer() {
            public void initialize(HttpRequest request) {
                GoogleHeaders headers = new GoogleHeaders();
                headers.setApplicationName("AndroidHive-Places-Test");
                request.setHeaders(headers);
                JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
                request.addParser(parser);
            }
        });
    }

}
